<!--
 * @Description: 登录组件
 * @Author: hai-27
 * @Date: 2020-02-19 20:55:17
 * @LastEditors: hai-27
 * @LastEditTime: 2020-03-01 15:34:08
 -->
<template>
  <div id="myLogin">
    <el-dialog title="登录" width="450px" center :visible.sync="isLogin">
      <el-form :model="LoginUser" :rules="rules" status-icon ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user-solid" placeholder="请输入账号" v-model="LoginUser.username"
                    maxlength="30" show-word-limit></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              prefix-icon="el-icon-view"
              type="password"
              placeholder="请输入密码"
              v-model="LoginUser.password"
              maxlength="30"
              show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="slideVerify">
          <center>
            <slide-verify
                ref="slideblock"
                :l="42"
                :r="10"
                :w="310"
                :h="155"
                @again="onAgain"
                @success="onSuccess"
                @fail="onFail"
                @refresh="onRefresh"
                :slider-text="text">
            </slide-verify>
            <div>{{ times }}</div>
          </center>
        </el-form-item>
        <el-form-item>
          <el-divider>其他登录方式</el-divider>
          <center>
            <el-button type="info" icon="el-icon-message" @click="isLogin=false;isEmail=true;" circle></el-button>
            <el-button type="info" icon="el-icon-mobile-phone" @click="LoginByPhone" circle></el-button>
            <el-button type="info" circle>
              <i-tencent-qq theme="outline" @click="wxLogin" size="14"/>
            </el-button>
            <el-button type="info" circle>
              <i-wechat theme="outline" @click="wxLogin" size="14"/>
            </el-button>
          </center>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" @click="Login" style="width:100%;">登录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :visible.sync="isEmail">
      <el-form title="邮箱登录" width="450px" center :model="LoginUserEmail" el-form-item label="短信验证" prop="phoneCode"
               :rules="rules2" ref="ruleForm2" class="pr">
        <el-form-item prop="email" >
          <el-input prefix-icon="el-icon-user-solid" placeholder="请输入邮箱" v-model="LoginUserEmail.email"
                    maxlength="30" show-word-limit></el-input>
          <button @click.prevent="getCode(LoginUserEmail.email)" class="code-btn" :disabled="!show">
            <span v-show="show">获取验证码</span>
            <span v-show="!show" class="count">{{ count }} s</span>
          </button>
        </el-form-item>
        <el-form-item prop="code">
          <el-input style="width:400px;" placeholder="请输入您接收的短信验证码" v-model="LoginUserEmail.code"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" @click="LoginEmail(LoginUserEmail)" style="width:100%;">登录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {mapActions} from "vuex";

export default {
  name: "MallLogin",
  data() {
    //图像验证码
    let validateSlid = (rule, value, callback) => {
      value = this.isValid;
      //console.log(value)
      if (!value) {
        return callback(new Error("请通过图像验证"));
      } else {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      }
    };
    // 用户名的校验方法
    let validateName = (rule, value, callback) => {
      //console.log(value)
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // 用户名以中文或字母开头,长度在1-30之间,允许字母数字下划线
      const userNameRule = /^[\u4E00-\u9FA5a-zA-Z0-9_]{1,30}$/;
      if (userNameRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(new Error("中文或字母开头,长度在1-30之间,允许字母数字下划线"));
      }
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以数字或字母开头,长度在5-30之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z0-9_]{5,30}$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
            new Error("数字或字母开头,长度5-30之间,允许字母数字和下划线")
        );
      }
    };
    /**
     * @邮箱登录校验方法
     * */
    let validateEmail = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入邮箱"));
      }
      // 密码以数字或字母开头,长度在5-30之间,允许字母数字和下划线
      const passwordRule = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
            new Error("请输入正确邮箱格式")
        );
      }
    };
    let validateCode = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入验证码"));
      }
      // 密码以数字或字母开头,长度在5-30之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z0-9_]{6}$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
            new Error("请输入6位的邮箱验证码")
        );
      }
    };
    return {
      //初始值
      show: 'false',
      count: '',
      /**
       * @邮箱登录框
       * */
      isEmail: false,
      /**
       * @滑块验证秒数
       * */
      times: '',
      /**
       * @滑块验证
       * */
      isValid: false,
      text: '向右拖动滑块填充拼图', //滑块底部文字
      LoginUser: {
        username: "",
        password: ""
      },
      LoginUserEmail: {
        email: "",
        code: ""
      },
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        username: [{validator: validateName, trigger: "blur"}],
        password: [{validator: validatePass, trigger: "blur"}],
        slideVerify: [{validator: validateSlid, trigger: "blur"}],
      },
      // 用户信息邮箱登录校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules2: {
        email: [{validator: validateEmail, trigger: "blur"}],
        code: [{validator: validateCode, trigger: "blur"}],
      },
    };
  },
  computed: {
    // 获取vuex中的showLogin，控制登录组件是否显示
    isLogin: {
      get() {
        return this.$store.getters.getShowLogin;
      },
      set(val) {
        this.$refs["ruleForm"].resetFields();
        this.setShowLogin(val);
      }
    }
  },
  mounted() {
    /*console.log(this.$route.query);
    var code = this.$route.query.code
    if(code!=null){
      console.log(66666);
      //如果用户扫码了自动进行回调方法
      this.$axios.post(this.$store.state.baseURL + 'client/' + this.$store.state.controller.Login
          + '/' + this.$store.state.mappings.wxCallBack+'?code='+this.$route.query.code)
          .then(res=>{
            //拿到用户信息
            console.log(res.data);
            if(res.data){
              //用户扫描后页面跳转
              this.$router.push({name:'client/Login/wx',params:{info:res.data}})
            }

          })
    }*/
  },
  methods: {
    ...mapActions(["setUser", "setShowLogin"]),
    /**
     * @判断是不是邮箱格式
     * */
    isEmailCode(val){
      if (val === "") {
        alert("请输入邮箱");
        return false;
      }
      // 密码以数字或字母开头,长度在5-30之间,允许字母数字和下划线
      const passwordRule = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (passwordRule.test(val)) {
        return true;
      } else {
        alert("请输入正确邮箱格式");
        return false;
      }
    },
    // 获取短信验证码
    getCode(val) {
        //如果通过校验开始登录
        if (this.isEmailCode(val)) {
          //axios请求
          this.$axios.get(this.$store.state.baseURL + 'client/' + this.$store.state.controller.Login
              + '/' + this.$store.state.mappings.sendEmail + '/' + val)
              .then(res => {
              })
              .catch(err => {
                console.log(err);
              })
          //console.log(this.LoginUserEmail.email);
          // 验证码倒计时
          if (!this.timer) {
            this.count = 60;
            this.show = false;
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= 60) {
                this.count--;
              } else {
                this.show = true;
                clearInterval(this.timer);
                this.timer = null;
              }
            }, 1000);
          }
        } else {
          return false;
        }
    },
    Login() {
      // 通过element自定义表单校验规则，校验用户输入的用户信息
      this.$refs["ruleForm"].validate(valid => {
        //如果通过校验开始登录
        if (valid) {
          const _this = this;
          this.$axios.get(_this.$store.state.baseURL + 'client/' + this.$store.state.controller.Login
              + '/' + this.$store.state.mappings.login + '/' + this.LoginUser.username + '/' + this.LoginUser.password)
              .then(res => {
                // “Accept”代表登录成功，其他的均为失败
                if (res.data.msg === "Accept!") {
                  // 隐藏登录组件
                  this.isLogin = false;
                  // 登录信息存到本地
                  let user = JSON.stringify(res.data.user);
                  localStorage.setItem("user", user);
                  let token = JSON.stringify(res.data.token);
                  localStorage.setItem("token", token);
                  // 登录信息存到vuex
                  this.setUser(res.data.user);
                  //this.setToken(res.data.token);
                  // 弹出通知框提示登录成功信息
                  this.notifySucceed(res.data.msg);
                } else {
                  // 清空输入框的校验状态
                  this.$refs["ruleForm"].resetFields();
                  // 弹出通知框提示登录失败信息
                  this.notifyError(res.data.msg);
                }
              })
              .catch(err => {
                return Promise.reject(err);
              });
        } else {
          return false;
        }
      });
    },
    onSuccess(times) {
      this.isValid = true;
      this.times = '耗时' + (times / 1000).toFixed(1) + 's';
    },
    onFail() {
      this.isValid = false;
    },
    onRefresh() {
      this.isValid = false;
    },
    onAgain() {
      //console.log('检测到非人为操作的哦！');
      // 刷新
      this.$refs.slideblock.reset();
    },
    /**
     * @短信验证码登录
     * */
    LoginByPhone() {
      alert('经费不足(T_T)');
    },
    /**
     * @微信登录二维码
     * */
    wxLogin() {
      alert('经费不足(T_T)');
      /*this.$axios.post(this.$store.state.baseURL + 'client/' + this.$store.state.controller.Login
          + '/' + this.$store.state.mappings.loginByWeChat)
          .then(res=>{
            console.log(res);
            //后台生成的url
            window.location.href = res.data;
          })
          .catch(err=>{
            console.log(err);
          })*/
    },
    /**
     * @邮箱登录
     * */
    LoginEmail(val) {
      this.$refs["ruleForm2"].validate(valid => {
        //如果通过校验开始登录
        if (valid) {
          this.$axios.get(this.$store.state.baseURL + 'client/' + this.$store.state.controller.Login
              + '/' + this.$store.state.mappings.loginByEmail + '/' + val.email + '/' + val.code)
              .then(res => {
                // “Accept”代表登录成功，其他的均为失败
                if (res.data.msg === "Accept!") {
                  // 隐藏登录组件
                  this.isEmail = false;
                  // 登录信息存到本地
                  let user = JSON.stringify(res.data.user);
                  localStorage.setItem("user", user);
                  let token = JSON.stringify(res.data.token);
                  localStorage.setItem("token", token);
                  // 登录信息存到vuex
                  this.setUser(res.data.user);
                  //this.setToken(res.data.token);
                  // 弹出通知框提示登录成功信息
                  this.notifySucceed(res.data.msg);
                } else {
                  // 清空输入框的校验状态
                  this.$refs["ruleForm"].resetFields();
                  // 弹出通知框提示登录失败信息
                  this.notifyError(res.data.msg);
                }
              })
              .catch(err => {
                return Promise.reject(err);
              });
        } else {
          return false;
        }
      });
    },
  },
  watch: {
    isLogin: function (val) {
      if (!val) {
        this.onAgain();
        this.times = "";
        this.isValid = false;
      }
    }
  }
};
</script>
<style>
.pr {
  position: relative;
}

.code-btn {
  width: 100px;
  height: 20px;
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 222;
  color: #409EFF;
  font-size: 14px;
  border: none;
  border-left: 1px solid #bababa;
  padding-left: 10px;
  background-color: #fff;
  cursor: pointer;
}
</style>